<template>
  <div class="carousel-manage">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">添加轮播图</el-button>
    </div>
    
    <el-table :data="carousels" style="width: 100%">
      <el-table-column prop="title" label="标题" />
      <el-table-column label="图片" width="180">
        <template #default="scope">
          <el-image 
            :src="scope.row.imageUrl" 
            :preview-src-list="[scope.row.imageUrl]"
            style="width: 100px; height: 60px" />
        </template>
      </el-table-column>
      <el-table-column prop="link" label="链接" />
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess">
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="form.link" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getCarousels, saveCarousel, updateCarousel, deleteCarousel } from '@/api/carousel'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const carousels = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userStore = useUserStore()
const router = useRouter()

// 检查权限
if (userStore.user?.role !== 1) {
  ElMessage.error('无权访问')
  router.push('/admin/dashboard')
}

const form = ref({
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1
})
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/api/file/upload'

const loadData = async () => {
  try {
    const res = await getCarousels()
    if (res.code === 200) {
      carousels.value = res.data
    }
  } catch (error) {
    console.error('Failed to load carousels:', error)
  }
}

const handleAdd = () => {
  form.value = {
    title: '',
    imageUrl: '',
    link: '',
    sort: 0,
    status: 1
  }
  dialogTitle.value = '添加轮播图'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.value = { ...row }
  dialogTitle.value = '编辑轮播图'
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个轮播图吗？')
    await deleteCarousel(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    console.error('Failed to delete carousel:', error)
  }
}

const handleSave = async () => {
  try {
    if (form.value.id) {
      await updateCarousel(form.value)
    } else {
      await saveCarousel(form.value)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('Failed to save carousel:', error)
  }
}

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.imageUrl = res.data
  }
}

const handleStatusChange = async (row) => {
  try {
    await updateCarousel(row)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('Failed to update status:', error)
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.operation-bar {
  margin-bottom: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 